#-*- coding: utf-8 -*-
'''
Created on Jun 24, 2012

@author: bbg
'''


from logic.login_session_mgr import LoginSessionMgr
from logic.cdkey_mgr import CdkeyManager 
import datetime
from core.db.companyx.user_right import UserRight
from core.db.company_management.company import Company
from core.db.company_management.rights import Rights 
from core.db.companyx.shop import Shop
import json
from core.util.debug import Log
import uuid
from webob import Request, Response
from service.server_config import SrvConfig

def application(environ, start_response):
    '''
        entrance of apache wsgi application
    '''    
    req = Request(environ)
    res = Response()
    
    LoginService.process(req, res)
    
    return res(environ, start_response)



class LoginService(object):
    __setup__ = False
    log = None    

    @staticmethod
    def process(req, res):
        if LoginService.__setup__ == False:
            Log.setPath(SrvConfig.getLogPath())
            LoginService.log = Log()            
            LoginService.__setup__ = True
            
        '''
            login application entrance, two types:
            1. client login
            2. web login
            3. logout
        '''
        
        try:
            loginType = req.params['type']
        except Exception,e:
            LoginService.log.e("LoginService:process, invalid type")
            res.json = {'ret':-1, 'msg':'invalid login type'}
            return

        try:
            dbsession = SrvConfig.getDefaultDBSession()    
            loginService = LoginService(dbsession)
            if loginType == '0': # client login
                return loginService.clientLogin(req, res)
            elif loginType == '1': # web login
                return loginService.webLogin(req, res)
            elif loginType == '2': #logout
                return loginService.logout(req, res)
            else:
                res.json = {'ret':-1, 'msg':'invalid login type:%d' % loginType}
    
        except Exception,e:
            LoginService.log.e("LoginService:process, exception:%s" % e)
            res.json = {'ret':-1, 'msg':'LoginService:process exception'}        
        finally:
            dbsession.close()
    

    def __init__(self, dbsession):
        self.dbsession = dbsession
    

    
    '''
    def applicationget(self, params,paths):
       
        #params = parse(None, environ)         
        client_type = params.getfirst('type')
        if client_type == '0': # client login
            return self._responseInvalidParam()
        elif client_type == '1': # web login
            return self._webgetcompany(params,paths)         
        return self._responseInvalidParam()
    '''


    '''
    #TODO:
    def applysub(self, params):

        #params = parse(None, environ)         
        client_type = params.getfirst('type')
        if client_type == '0': # client login
            return self._responseInvalidParam()
        elif client_type == '1': # web login
            return self._webapplysub(params)         
        return self._responseInvalidParam()
    '''


    def clientLogin(self, req, res):
        '''
            负责客户端的登陆操作
        '''
        try:            
            cdkey = req.params['cdkey']
            uuid = req.params['uuid']
            username = req.params['username']
            pwd = req.params['pwd']           
                    
            if cdkey == None or uuid == None or username == None or pwd == None:
                LoginService.log.e("LoginService:clientLogin, param incomplete, cdkey:%s, uuid:%s, username:%s, pwd:%s"
                             % (cdkey, uuid, username, pwd))
                res.json = {'ret':-1, 'msg':'param incomplete'}
                return
            
            #check cdkey mapping
            cdkeyInfo = CdkeyManager.getCdkeyInfo(cdkey, self.dbsession)
            if cdkeyInfo == None:
                LoginService.log.e("LoginService:clientLogin, no such cdkey:%s" % cdkey)
                res.json = {'ret':103, 'msg':'cdkey not exists'}
                return
        
            if CdkeyManager.isValid(cdkey, uuid, self.dbsession) is False:
                #response cdkey invalid, login failed
                LoginService.log.e("LoginService:clientLogin, cdkey illegal, cdkey:%s" % cdkey) 
                res.json = {'ret':104, 'msg':'cdkey invalid'}
                return
            
            #login
            company_id = cdkeyInfo.company_id
            odno_id = cdkeyInfo.state
            
            self._login(company_id, username, pwd, odno_id, res)
        except Exception,e:
            LoginService.log.e("LoginService:clientLogin, Exception:%s" % e)
            res.json = {'ret':-1, 'msg':'unknown exception'}
          

    def webLogin(self, req, res):
        '''
            负责web端的登陆操作
        '''        
        company_id = req.params['company_id'] 
        username = req.params['username']
        pwd = req.params['pwd']
        
        if company_id == None or username == None or pwd == None:
            LoginService.log.e("LoginService:.webLogin, invalid param, company_id:%s, username:%s, pwd:%s" 
                         % (company_id, username, pwd))
            res.json = {'ret':-1, 'msg':'invalid params'}
            return

        isValid = LoginSessionMgr.isValidCompanyid(company_id, self.dbsession)
        if isValid == False:     
            LoginService.log.e("LoginService:.webLogin, invalid company id:%s" % company_id)  
            res.json = {'ret':-1, 'msg':'no company id'}
            return
        
        odno_id = 0;
          
        self._login(company_id, username, pwd, odno_id, res)          
        
    '''    
    #TODO: check      
    获取某个公司的所有分店信息
    def _getshopx(self,company_id,dbsession,request_params):
        danqian_id = request_params.getfirst('danqian_id')    
        username = request_params.getfirst('username')         
        token = request_params.getfirst('token')
 
        if danqian_id == None or token == None or username==None or company_id==None:
            return self._responseInvalidParam()
        
        #核实企业ID是否存在
        dbsession = self._returndbsession()
        intcomp=LoginSessionMgr.isValidCompanyid(danqian_id, dbsession)
        if intcomp== False:
            self.debug.e("LoginService._getshopx: no such company id:%s" % company_id)
            return self._responseError(-1, 'no company id ')
        
        intcomp = LoginSessionMgr.isValidSession(danqian_id, username, token, dbsession)        
        if intcomp==False:
            response_params = {}
            response_params['ret'] =107
            response_params['msg'] = 'session expired'            
            return self._response(json.dumps(response_params))

        Shop.doMapping(company_id)
        shops = dbsession.query(Shop).filter(Shop.id >= 0)
        dbsession.commit()
        
        response_paramsARRAY = []   
        response_params={}
        response_params['ret'] =0
        response_params['msg'] = 'success'
     
        for row in shops:
            response_paramsb = {}
            response_paramsb["name"]=row.name
            response_paramsb["address"]=row.address
            response_paramsb["contact"]=row.contact
            response_paramsb["phone"]=row.phone
            response_paramsb["fax"]=row.fax
            response_paramsb["email"]=row.email       
            response_paramsb["id"]=row.id   
            response_paramsb["note"]=row.note                   
            response_paramsb["state"]=row.state                                          
            strtemp=json.dumps(response_paramsb)
            response_paramsARRAY.append(strtemp)  
        
        
        response_params['data']=response_paramsARRAY    
        return self._response(json.dumps(response_params))
    '''  
          
 
    '''    
    #TODO: check      
    def _webgetcompany(self, request_params,paths):
       
        dbsession = self._returndbsession()
        company_id = request_params.getfirst('company_id')
        if paths[1]=="shopsh":
            return self._getshopx(company_id,dbsession,request_params)
        else:
            self.debug.e("LoginService._webgetcompany invalid path:%s" % repr(paths))
            return self._responseInvalidParam()
    '''
 
                    
    '''                
    #TODO: check                                                  
    def _webapplysub(self, request_params):
        
        #    负责web端的申请服务
                
        name = request_params.getfirst('name')
        address = request_params.getfirst('address')         
        yyzz = request_params.getfirst('yyzz')
        contact = request_params.getfirst('contact')
        phone = request_params.getfirst('phone')
        jytype = request_params.getfirst('jytype')
        jyguimo = request_params.getfirst('jyguimo')    
        email= request_params.getfirst('email')          
        if name == None or address == None or yyzz== None or contact==None or phone==None or jytype==None or jyguimo==None :
            return self._responseInvalidParam()
         
        #核实企业ID是否存在
        dbsession =self._returndbsession()
        intcomp=LoginSessionMgr.HasApplyed(name,yyzz,contact,phone,dbsession)
        if intcomp== True:
            self.debug.e("LoginService._webapplysub: already exist, name:%s, address:%s" % (name, address))
            return self._responseError(-1,"already exist")
                         
        tempuuid=uuid.uuid4()
        company =Company()      
        company.name=name
        company.address=address
        company.contact=contact
        company.phone=phone
        company.jytype=jytype
        company.email=email
        company.jyguimo=jyguimo
        company.yyzz=yyzz
        company.uuid=tempuuid
        dbsession.add(company)
        dbsession.commit()
        
        companyb=dbsession.query(Company).filter(Company.uuid == tempuuid)
        dbsession.commit()
        response_paramsARRAY = []   
        for row in companyb:
            response_paramsb = {}
            response_paramsb["ret"]=0
            response_paramsb["msg"]="申请已经提交，企业ID：%d "  % row.id
            strtemp=json.dumps(response_paramsb)
            response_paramsARRAY.append(strtemp)      
        #response_paramsARRAY.append(response_params)
        return self._response(json.dumps(response_paramsARRAY)) 
    '''                   


    def _login(self, company_id, username, pwd, odno_id, res):
        '''
            real login
        ''' 
        ret = LoginSessionMgr.login(company_id, username, pwd, self.dbsession)

        if ret[0] == 0:
            token = ret[1]
            user_id = ret[2]
            shop_id = ret[3]
            user_name = ret[4]
            right_level = ret[5]
            realname = ret[6]
        elif ret[0] == -1 or ret[0] == -2 or ret[0] == -3:
            res.json = {'ret':-1, 'msg':ret[1]}
            return
        
        #get user rights
        rights = self._getUserRights(company_id, user_id)
        company_name = self._getCompanyName(company_id)
        shop_name = self._getShopName(company_id, shop_id)
         
        res.json = {
                    'ret':0,
                    'token': token,
                    'rights':rights,
                    'userid': user_id,
                    'username': user_name,
                    'company_id': company_id,
                    'odno_id': odno_id,
                    'shop_id': shop_id,
                    'right_level': right_level,
                    'realname': realname,
                    'company_name': company_name,
                    'shop_name': shop_name,
                    'serverdatetime': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                    }               
        
        LoginService.log.d("LoginService._login: user %s login ok" % user_name)      
        
                            
    def _getUserRights(self, company_id, user_id):
        
        UserRight.doMapping(company_id)
        
        rights = self.dbsession.query(UserRight).filter(UserRight.user_id == user_id)
        self.dbsession.commit()
        
        right_names = []
       
        for right in rights:
            response_paramsb={}
            response_paramsb["name"] = right.right_name
            rightsyuanshi = self.dbsession.query(Rights).filter(Rights.name == right.right_name)
            self.dbsession.commit()
            rightsyuanshi.first()
            if rightsyuanshi.count() == 0:
                response_paramsb["note"] = right.right_name
            else:
                response_paramsb["note"] = rightsyuanshi[0].note
        
            strtemp = json.dumps(response_paramsb)
            right_names.append(strtemp)
                       
        return right_names
    
    
    
    def _getCompanyName(self, company_id):
        company = self.dbsession.query(Company).filter(Company.id == company_id)        
        self.dbsession.commit()
        
        if company.count() == 0:
            return company_id
        return company.first().name        
        

    def _getShopName(self, company_id,shop_id):
        Shop.doMapping(company_id)
        shop = self.dbsession.query(Shop).filter(Shop.id == shop_id)        
        self.dbsession.commit()
        
        if shop.count() == 0:
            return shop_id
        
        return shop.first().name
        
    '''
    #TODO: check     
    def _getCompanyData(self, company_id, username, pwd):

        res = LoginSessionMgr.login(company_id, username, pwd)
        response_params = {}
        if res[0] == 0:
            response_params['token'] = res[1]
            user_id = res[2]
            shop_id = res[3]
        elif res[0] == -1 or res[0] == -2 or res[0] == -3:
            response_params['ret'] = -1
            response_params['msg'] = res[1]
            return self._response(json.dumps(response_params))
        
        #get user rights
        rights = self._getUserRights(company_id, user_id)
                        
        response_params['ret'] = 0
        response_params['rights'] = rights
        response_params['user_id'] = user_id  
        response_params['company_id'] = company_id
        response_params['shop_id'] = shop_id      
        return self._response(json.dumps(response_params))         
    '''
     
    def logout(self, req, res):        
        company_id = req.params['company_id'] 
        username = req.params['username']
        token = req.params['token']
        
        if LoginSessionMgr.logout(company_id, username, token, self.dbsession) == True:
            res.json = {'ret':0, 'msg':'logout ok'}
        else:
            res.json = {'ret':-1, 'msg':'logout failed'}
        
        
